<template>
  <div>
    <el-dialog title="修改用户" :visible.sync="isShow" width="800px" :close-on-click-modal="false" @close="closeUserMod"
      @open="openUpdate">
      <div v-loading="loading">
        <el-card>
          <el-form size="mini" ref="newUserDate" :model="newUserDate" :rules="rules" label-width="100px"
            label-position="left">
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="userNum" label="用户编号:">
                  <el-input v-model="newUserDate.userNum" :disabled="true" placeholder="请输入用户编号"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item prop="tellerNo" label="柜员号:">
                  <el-input v-model="newUserDate.tellerNo"  placeholder="请输入柜员号"></el-input>
                </el-form-item>
              </el-col> -->
            <!-- </el-row>
            <el-row :gutter="30"> -->
              <el-col :span="12">
                <el-form-item prop="branchId" label="所属机构:">
                  <el-select v-model="newUserDate.branchId" >
                    <el-option v-for="item in brnoList" :key="item.value" :label="item.cname" :value="item.orgno"
                      >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="userStates" label="用户状态:">
                  <el-select v-model="newUserDate.userStates">
                    <el-option v-for="item in userStatesList" :key="item.value" :label="item.label" :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="userName" label="用户名称:">
                  <el-input v-model="newUserDate.userName" placeholder="请输入用户名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="engName" label="英文名称:">
                  <el-input v-model="newUserDate.engName" placeholder="请输入英文名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="sex" label="性别:">
                  <el-select v-model="newUserDate.sex">
                    <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item prop="emailAddress" label="邮箱:">
                  <el-input v-model="newUserDate.emailAddress" placeholder="请输入邮箱"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="certType" label="证件类型:">
                  <el-select v-model="newUserDate.certType">
                    <el-option v-for="item in certTypeList" :key="item.DataKeyVal"
                    :label="item.Meaning"
                    :value="item.DataKeyVal"
                    :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="certNum" label="证件号码:">
                  <el-input v-model="newUserDate.certNum" placeholder="请输入证件号码"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="telephone" label="手机号:">
                  <el-input v-model="newUserDate.telephone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="contactNum" label="联系电话:">
                  <el-input v-model="newUserDate.contactNum" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item prop="contactAddr" label="联系地址:">
                  <el-input v-model="newUserDate.contactAddr" placeholder="请输入联系地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="userLevel" label="用户级别:">
                  <el-select v-model="newUserDate.userLevel">
                    <el-option v-for="item in userLevelList" :key="item.DataKeyVal"
                    :label="item.Meaning"
                    :value="item.DataKeyVal"
                    :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="生效日期" prop="startdate">
                  <el-date-picker v-model="newUserDate.startdate" :disabled="true" :editable=false value-format="yyyyMMdd" type="date"
                    placeholder="选择生效日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="失效日期" prop="enddate">
                  <el-date-picker v-model="newUserDate.enddate" :editable=false value-format="yyyyMMdd" type="date"
                    placeholder="选择失效日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="30">
              <el-col :span="12">
                  <el-form-item prop="certtp" label="认证方式（统一登录平台）">
                    <el-select v-model="newUserDate.certtp">
                      <el-option v-for="item in certtpList" :key="item.value" :label="item.label" :value="item.value"
                        :disabled="item.disabled">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
              <!-- <el-col :span='24'>
              <el-form-item label="用户类型" prop="usertype">
                <el-radio-group v-model="newUserDate.usertype">
                  <el-radio :label=true>V端用户</el-radio>
                  <el-radio :label=false>C端用户</el-radio>
                </el-radio-group>
              </el-form-item>
              </el-col> -->
            <!-- </el-row> -->
          </el-form>
        </el-card>
        <div style="text-align:right;margin:20px 0">
          <el-button size="mini" @click="cancleUserMod">取消</el-button>
          <el-button type="primary" @click="userMod" size="mini">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import createUser from "@/message/userManage/user/user-create";
  import branchList from "@/message/shared/branch-list";
  import selectLoad from "@/message/shared/dict-select-load";
  import toolBox from "@/common/utils/toolBox";
  import request from "@/common/utils/request";
  import modUser from "@/message/userManage/user/user-update";
  import InquireUser from "@/message/userManage/user/userinfo-load";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  export default {
    name: "create-user",
    data() {
      //表单自定义校验
      let validatorPhone = (rule, value, callback) => {
        if (value != "") {
          let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入正确的手机号"));
          }
        } else {
          callback();
        }
      };
      let validatorEmail = (rule, value, callback) => {
        if (value != "") {
          let reg = new RegExp(
            "^[a-zA-Z0-9]+([._\\-]*[a-zA-Z0-9])*@([a-zA-Z0-9]+[-a-zA-Z0-9]*[a-zA-Z0-9]+.){1,63}[a-zA-Z0-9]+$"
          );
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入正确的邮箱"));
          }
        } else {
          callback();
        }
      };
      let expiDateChek = (rule, value, callback) => { //自定义表单验证 校验IP地址
      console.log(value);
        if (value != "") {
          if (value - this.newUserDate.startdate >= 0) {
            callback();
          } else {
            callback(new Error("失效日期必须大于生效日期"));
          }
        } else {
          callback();
        }
      };
      return {
        loading: false,
        brnoList: [],
        sexList: [{
          label: '男',
          value: '0'
        }, {
          label: '女',
          value: '1'
        }],
        certtpList: [
        {
          label: "密码",
          value: "0"
        },
        {
          label: "指纹",
          value: "2"
        }
      ],
        userStatesList: [],
        certTypeList: [],
        userLevelList: [],
        newUserDate: { //表单信息
          userNum: "",
          userName: "",
          engName: "",
          branchId: "",
          sex: "0",
          certType: "",
          certNum: "",
          tellerNo: "",
          userStates: "",
          contactNum: "",
          contactAddr: "",
          telephone: "",
          emailAddress: "",
          userLevel: "",
          startdate: "",
          enddate: "",
          usertype:true,
          certtp: ""
        },
      rules: {
        //校验对象
        // userID: [
        //   { required: true, message: "请输入用户编号", trigger: "blur" }
        // ],
        branchId: [
          {
            required: true,
            message: "请选择机构号",
            trigger: "change"
          }
        ],
        userStates:[
          {
            required: true,
            message: "请选择用户状态",
            trigger: "change"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "blur"
          },
          {
            max: 200,
            message: "用户名称长度少于200个字符",
            trigger: "blur"
          }
        ],
        // remark: [{ max:10, message: "请输入少于120位字符", trigger: "blur" }],
        telephone: [
          {
            message: "手机号长度少于20个字符",
            max: 20,
            trigger: "blur"
          },
          {
            require: false,
            validator: validatorPhone,
            trigger: "blur"
          }
        ],
        emailAddress: [
          {
            max: 20,
            message: "邮箱长度少于20个字符",
            trigger: "blur"
          },
          {
            require: false,
            validator: validatorEmail,
            trigger: "blur"
          }
        ],
        userNum: [
          {
            required: true,
            message: "请输入用户编号",
            trigger: "blur"
          },
          {
            max: 10,
            message: "请输入正确工号，长度少于10个字符",
            trigger: "blur"
          }
        ],
        userLevel: [
          {
            required: true,
            message: "请选择用户级别",
            trigger: "change"
          }
        ],
        startdate: [
          {
            required: true,
            message: "请选择生效日期",
            trigger: "change"
          }
        ],
        enddate: [
          {
            required: true,
            message: "请选择失效日期",
            trigger: "change"
          },
          {
              validator: expiDateChek,
              trigger: "change"
            }
        ],
        tellerNo: [
          {
            required: true,
            message: "请输入柜员号",
            trigger: "blur"
          },
          {
            max: 20,
            message: "请输入正确柜员号，长度少于20个字符",
            trigger: "blur"
          }
        ]
      }
      };
    },
    props: { //父元素传递的数据
      optionUpdate: Object
    },
    computed: {
      isShow: { //修改用户弹窗是否显示
        get: function () {
          return this.optionUpdate.isShow;
        },
        set: function (newValue) {
          this.optionUpdate.isShow = newValue;
        }
      },
    },
    methods: {
      initList() { //初始化下拉列表
        let resBody = new branchList();
        resBody.data.orgno = this.$store.getters.BranchNum;
        request(resBody)
          .then(response => {
            this.loading = false;
            this.brnoList = response.RspInfo.Result || [];
          })
          .catch(error => {
            this.loading = false
            console.error("错误信息", error);
          });
      },
      loadCertTypeList() {
        let resBody = new selectLoad();
        resBody.data.DataKey = 'CtfTp';
        request(resBody)
          .then(response => {
            this.certTypeList = response.RspInfo.Result || [];
          })
          .catch(error => {
            this.loading = false
            console.error("错误信息", error);
          });
      },
      loadUserLevelList() {
        let resBody = new selectLoad();
        resBody.data.DataKey = 'TlrLevel';
        request(resBody)
          .then(response => {
            this.userLevelList = response.RspInfo.Result || [];
          })
          .catch(error => {
            this.loading = false
            console.error("错误信息", error);
          });
      },
      userInfoLoad(userNum) {
        let resBody = new InquireUser();
        resBody.data.UserNum = userNum;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              let userInfo = response.RspInfo.Result[0];
              this.newUserDate.userNum = userInfo.UserNum;
              this.newUserDate.userName = userInfo.UserName;
              this.newUserDate.engName = userInfo.EngName;
              this.newUserDate.branchId = userInfo.BranchNum;
              this.newUserDate.sex = userInfo.Gender;
              this.newUserDate.userStates = userInfo.UserStatus;
              this.newUserDate.certType = userInfo.CertType;
              this.newUserDate.certNum = userInfo.CertNum;
              this.newUserDate.tellerNo = userInfo.CashierCardNum;
              this.newUserDate.contactNum = userInfo.ContactNum;
              this.newUserDate.contactAddr = userInfo.ContactAddr;
              this.newUserDate.telephone = userInfo.PhoneNum;
              this.newUserDate.emailAddress = userInfo.Mailbox;
              this.newUserDate.userLevel = userInfo.UserLevel;
              this.newUserDate.startdate = userInfo.EnableDate;
              this.newUserDate.enddate = userInfo.TermDate;
              this.newUserDate.certtp = userInfo.certtp;
            }

          })
          .catch(error => {
            this.loading = false;
          });
      },
      openUpdate() { //打开弹窗事件
        this.userStatesList = toolBox.objToArray(getGlobalParams.get("UserStates"));
        this.initList();
        this.loadCertTypeList();
        this.loadUserLevelList();
        this.userInfoLoad(this.optionUpdate.currentRow.UserNum);
      },
      cancleUserMod() { //关闭弹窗事件，清楚表单验证
        this.optionUpdate.isShow = false;
        this.$refs.newUserDate.clearValidate();
      },
      closeUserMod() { //修改弹窗关闭
        this.$refs.newUserDate.clearValidate();
      },
      userMod() { //修改用户
        this.$refs["newUserDate"].validate(valid => {
          if (valid) {
            this.loading = true;
            let resBody = new modUser();
            resBody.data.UserNum = this.newUserDate.userNum;
            resBody.data.UserName = this.newUserDate.userName;
            resBody.data.BranchNum = this.newUserDate.branchId;
            resBody.data.EngName = this.newUserDate.engName;
            resBody.data.EnableDate = this.newUserDate.startdate;
            resBody.data.TermDate = this.newUserDate.enddate;
            resBody.data.CertType = this.newUserDate.certType;
            resBody.data.CertNum = this.newUserDate.certNum;
            resBody.data.Gender = this.newUserDate.sex;
            resBody.data.UserStatus = this.newUserDate.userStates;
            resBody.data.ContactNum = this.newUserDate.contactNum;
            resBody.data.PhoneNum = this.newUserDate.telephone;
            resBody.data.ContactAddr = this.newUserDate.contactAddr;
            resBody.data.Mailbox = this.newUserDate.emailAddress;
            resBody.data.CertType = this.newUserDate.certType;
            resBody.data.UserLevel = this.newUserDate.userLevel;
            resBody.data.CashierCardNum = this.newUserDate.tellerNo;
            resBody.data.certtp = "0";
            request(resBody)
              .then(response => {
                if (response.SYS_HEAD.ReturnCode === "000000") {
                  this.loading = false;
                  this.$message({
                    type: "success",
                    message: "用户修改成功!"
                  });
                  this.optionUpdate.isShow = false;
                  this.$emit("refreshTable"); //修改用户成功并刷新表格数据
                } else {
                  this.$message({
                    type: "error",
                    message: `${response.SYS_HEAD.ReturnMessage}!`
                  });
                  this.loading = false;
                }
              })
              .catch(error => {
                this.loading = false;
              });
          } else {
            this.$message({
              type: "warning",
              message: "请输入合法的数据！"
            });
            return false;
          }
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  .content {
    display: flex;
    flex-direction: column;
  }

  .require {
    color: red;
  }

  .dialog-text {
    display: inline-block;
    width: 100%;
    text-align: center;
    color: red;
    font-size: 18px;
  }

  .role {
    width: 95%;
    border: 1px solid #eee;
    border-radius: 4px;
    height: 290px;

    .roleHeader {
      color: #606266;
      font-weight: 500;
      font-size: 14px;
      background: #f5f7fa;
      height: 42px;
      box-sizing: border-box;
      padding: 9px;
      overflow-y: auto;
    }
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%
  }
  .el-dialog__body {
    padding: 20px;
    padding-top: 10px;
  }

  .el-card {
    overflow: inherit;
  }

</style>
